package block

import (
	"bytes"
	"encoding/hex"
	"fmt"
	"os"
	"time"
)

/**
命令行cli的功能实现
*/

func (cli *CLI) PrintChain() {
	bc := NewBlockChain()
	if bc == nil {
		return
	}
	defer bc.Db.Close()
	it := bc.NewInterator()
	fmt.Println("=============开始读取数据库==================")
	for {
		block1 := it.Next()
		fmt.Println("---------------------------------------------")
		fmt.Println("PrevBlockHash:", hex.EncodeToString(block1.PrevBlockHash))
		fmt.Println("this Hash:", hex.EncodeToString(block1.Hash))
		//fmt.Println("Transaction[0]:", block1.Transaction[0].TXInputs[0])
		fmt.Println("Transaction:", block1.Transactions[0].TXInputs[0].Pubkey)
		fmt.Println("TimeStamp:", time.Unix(int64(block1.TimeStamp), 0).Format("2006/01/02 15:04"))
		fmt.Println("Difficulity:", block1.Difficulity)
		fmt.Println("Nonce:", block1.Nonce)
		pow := NewProofOfWork(block1)
		fmt.Println("校验是否成功！", pow.IsValid())
		fmt.Println("---------------------------------------------")
		if bytes.Equal(block1.PrevBlockHash, []byte{MainBlockName}) {
			fmt.Println("区块链遍历结束")
			break
		}
	}
}

//"转账命令(FROM付款人，TO收款人，AMOUNT金额，MINER矿工)"
func (cli *CLI) Send(from string, to string, amount float64, miner string, data string) {

	if !IsValidAddress(from) {
		fmt.Println("地址：",from,",是无效地址！")
	}


	if !IsValidAddress(to) {
		fmt.Println("地址：",to,",是无效地址！")
	}

	if !IsValidAddress(miner) {
		fmt.Println("地址：",miner,",是无效地址！")
	}
	// 流程
	// 创建挖矿交易
	// 创建普通交易
	// 添加到区块
	bc := NewBlockChain()
	if bc == nil {
		return
	}
	defer bc.Db.Close()
	txs := []*Transaction{}
	// 创建挖矿交易
	//coinbase := NewCoinbaseTx(miner, "非创世区块信息,可自定义")
	coinbase := NewCoinbaseTx(miner, data)
	txs = append(txs, coinbase)
	// 创建普通交易
	tx := NewTransaction(from, to, amount, bc)
	if tx != nil {
		txs = append(txs, tx)
	} else {
		fmt.Println("交易无效，请核对报错信息，可重新发起交易。")
	}
	// 添加交易到区块
	bc.AddBlock(txs)
	fmt.Println("交易完成，请等待矿工交易完成。")
}

//创建区块链
func (cli *CLI) CreateBlockChain(addr string) {
	if !IsValidAddress(addr) {
		fmt.Println("地址：",addr,",是无效地址！")
	}
	bc := CreateBlockChain(addr)
	if bc == nil {
		return
	}
	defer bc.Db.Close()
	if bc == nil {
		fmt.Println("创建失败！，请删除当前目录.db文件")
		os.Exit(1)
	}
	fmt.Println("创建区块链成功！")
}

func (cli *CLI) GetBalance(addr string) {
	if !IsValidAddress(addr) {
		fmt.Println("地址：",addr,",是无效地址！")
	}
	bc := NewBlockChain()
	if bc == nil {
		return
	}
	defer bc.Db.Close()
	bc.GetBalance(addr)
}
//临时
func (cli *CLI) CreateWallet() {
	ws:=NewWallets()
	address:=ws.CreateWallet()
	fmt.Println("创建钱包地址为：",address)
}

func (cli *CLI)ListAddress()  {
	ws:=NewWallets()
	keys:=ws.ListAddress()
	for _,address:=range keys{
		fmt.Println("钱包地址：address=",address)
	}
}

func (cli *CLI)PrintTx()  {
	bc := NewBlockChain()
	if bc == nil {
		return
	}
	defer bc.Db.Close()
	it := bc.NewInterator()
	fmt.Println("=============开始读取数据库==================")
	for {
		block1 := it.Next()
		fmt.Println("\n+++++++++++++++++++++++++++++++++++++++\n")
		for _,tx:=range block1.Transactions{
			fmt.Println(tx)
		}
		if bytes.Equal(block1.PrevBlockHash, []byte{MainBlockName}) {
			fmt.Println("区块链遍历结束")
			break
		}
	}
}